package com.zyl.ag.manager;  
import java.util.ArrayList;
import java.util.List;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.util.Log;

import com.zyl.ag.bean.Account;
import com.zyl.ag.bean.Record;
import com.zyl.util.CalUtil;
import com.zyl.util.DBHelper;

/**
 * 题库
 * @param  
 * @return
 */
public class RecordManager {  
      
        private DBHelper helper;  
     
        
        
        public RecordManager(Context context) {  
            helper = new DBHelper(context);//初始化数据库  
         
        }  
      
       
    	private Record rowMapper(Cursor cursor) {
    		Integer id = cursor.getInt(	cursor.getColumnIndex("_id"));
    		String name = cursor.getString(	cursor.getColumnIndex("name"));
    		Integer course_id = cursor.getInt(cursor.getColumnIndex("course_id"));
    		Integer downloadcount = cursor.getInt(cursor.getColumnIndex("downloadcount"));
    		Integer sort_order = cursor.getInt(cursor.getColumnIndex("sort_order"));
    		Integer type = cursor.getInt(cursor.getColumnIndex("type"));
    		Integer status = cursor.getInt(cursor.getColumnIndex("status"));
    		Integer favor = cursor.getInt(cursor.getColumnIndex("favor"));
    		String photo = cursor.getString(cursor.getColumnIndex("photo"));
    		String url = cursor.getString(cursor.getColumnIndex("url"));

    		
    		Record l =new Record();	
    		l.set_id(id);
    	 
    		return l;
    	}
        /**  
         * 查询所有Record对象  
         * @return Record对象集合, 如未找到, 返回一个size()为0的List  
         */  
        public List<Record> findAll() {  
            SQLiteDatabase db = helper.getReadableDatabase();  
            Cursor cursor = db.rawQuery("SELECT id,title,answer,appearTimes FROM Record", null);  
            List<Record> Records = new ArrayList<Record>();  
            while (cursor.moveToNext()) {  
                Integer id = cursor.getInt(0);  
                String title = cursor.getString(1);  
                String answer = cursor.getString(2);  
                Integer appearTimes = cursor.getInt(3);  
                Records.add(new Record());  
            }  
            cursor.close();  
            db.close();  
            return Records;  
        }  
        public Integer findMoneyByName(String name) {
			
			
			//如果是买入的话 就减去 r.getPrice
			//如果是卖出的话 就加上 r.getPrice
			   SQLiteDatabase db = helper.getReadableDatabase();  
	            Cursor cursor = db.rawQuery("SELECT money FROM account where name=?", new String[] { name});  
	            Integer money =0;
	            while (cursor.moveToNext()) {  
	                  money = cursor.getInt(0);  
	            }  
	            cursor.close();  
	            db.close();  
	            return money;  
			
		}
        public  List<Record> findRecord(String username,int t  ,int d,int n ) {
        	 List<Record> records = new ArrayList<Record>(); 
        	
        	//如果是买入的话 就减去 r.getPrice
        	//如果是卖出的话 就加上 r.getPrice
        	SQLiteDatabase db = helper.getReadableDatabase();  
        	Cursor  cursor = db.rawQuery("SELECT _id,name,num,price,type,deal,money,date FROM record where name=? and type =? and deal =? order by _id desc  limit ? ", new String[] { username,t+"",d+"",n+""}); 
        	 
        	while (cursor.moveToNext()) {  
                Integer id = cursor.getInt(0);  
                String name = cursor.getString(1);  
                Integer num = cursor.getInt(2);  
                Integer price = cursor.getInt(3);  
                Integer type = cursor.getInt(4);  
                Integer deal = cursor.getInt(5);  
                Integer money = cursor.getInt(6);  
                String date = cursor.getString(7);  
                Record	r =new Record(  name,  num,   price,
						  type,   deal,   money,   Long.parseLong(date ));
                records.add(r);
             
                
            }  
        	cursor.close();  
        	db.close();  
        	return records;  
        	
        }
     	public void updateMoneyByName(String name,Integer money) {
//			   SQLiteDatabase db = helper.getReadableDatabase();  
//	            Cursor cursor = db.rawQuery("update account set money =?  where name='"+name+"' ", new String[] { money +"" });  
//	            cursor.close();  
//	            db.close();  
	            
	            SQLiteDatabase db = helper.getWritableDatabase(); 
				   
				   
	 		   //获取到数据库  
	             db.execSQL("update account set money =?  where name=? ", new String[] { money +"",name });
	             db.close();  
	            
		}
		public void add(Record r) {
			String name =r.getName();
			Integer money = findMoneyByName(name);
			//如果是买入的话 就减去 r.getPrice
			//如果是卖出的话 就加上 r.getPrice
			
			int c =(int)CalUtil.tip(r.getPrice())*r.getNum();
			
			
			Record trade =findTrade(r);
			
		
			if(r.getType()==1){
				//多单
				if(r.getDeal()==1){
					//多单买入开仓
					money=money-r.getMoney() -c;
					
					trade.setNum(trade.getNum()+r.getNum());
					trade.setPrice(trade.getPrice()+r.getPrice()*r.getNum());
					trade.setMoney(trade.getMoney()+r.getMoney() );
				}else{
					//多单卖出平仓
					money=money-c;
					 if(r.getNum()<=trade.getNum()){
							money+=trade.getMoney()*r.getNum()/trade.getNum()+(r.getPrice()-trade.getPrice()/trade.getNum())*r.getNum();
							trade.setPrice(trade.getPrice()-trade.getPrice()*r.getNum()/trade.getNum());
							trade.setMoney(trade.getMoney()-trade.getMoney()*r.getNum()/trade.getNum());
							trade.setNum(trade.getNum()-r.getNum());
					 }
				}
			}else{
				if(r.getDeal()==1){
					//空单买入平仓
					money=money-c;
					 if(r.getNum()<=trade.getNum()){
						 
							money+=trade.getMoney()*r.getNum()/trade.getNum()+(trade.getPrice()/trade.getNum()-r.getPrice())*r.getNum();
							
							trade.setPrice(trade.getPrice()-trade.getPrice()*r.getNum()/trade.getNum());
							trade.setMoney(trade.getMoney()-trade.getMoney()*r.getNum()/trade.getNum());
							trade.setNum(trade.getNum()-r.getNum());
					 }
				}else{
					//空单卖出开仓
					money=money-r.getMoney() -c;
					
					trade.setNum(trade.getNum()+r.getNum());
					trade.setPrice(trade.getPrice()+r.getPrice()*r.getNum());
					trade.setMoney(trade.getMoney()+r.getMoney() );
				}
			}
		    updateTrade(trade);
			updateMoneyByName(  name,  money);
			
			SQLiteDatabase db = helper.getWritableDatabase(); 
			   
			   
		   //获取到数据库  
            db.execSQL("INSERT INTO Record(name,num,price,type,deal,money,date) VALUES(?,?,?,?,?,?,?)", 
            		new Object[] { r.getName(),r.getNum(),r.getPrice(),r.getType(),r.getDeal(),r.getMoney(),r.getDate() });  
            db.close();  
			
		}
		public void addTrade(Record r) {
			SQLiteDatabase db = helper.getWritableDatabase(); 
		   //获取到数据库  
            db.execSQL("INSERT INTO trade(name,num,price,type,deal,money,date) VALUES(?,?,?,?,?,?,?)", 
            		new Object[] { r.getName(),r.getNum(),r.getPrice(),r.getType(),r.getDeal(),r.getMoney(),r.getDate() });  
            db.close();  
			
		}
		public void updateTrade(Record r) {
			SQLiteDatabase db = helper.getWritableDatabase(); 
			//获取到数据库  
			db.execSQL("update trade  set  num= "+r.getNum()+",price= "+r.getPrice()+",money= "+r.getMoney()+" where name='"+ r.getName()+"' and type= "+r.getType()+" and deal= "+r.getDeal()+" ");  
			db.close();  
			
		}
		 
			public  Record findTrade(Record re) {
				 
	        	SQLiteDatabase db = helper.getReadableDatabase();  
	        	Cursor  cursor = db.rawQuery("SELECT _id,name,num,price,type,deal,money,date FROM trade where name=? and type =? and deal =? order by _id desc  limit 1 ", new String[] { re.getName() ,re.getType() +"",re.getType()+""}); 
	        	Record	r =null; 
	        	while (cursor.moveToNext()) {  
	                Integer id = cursor.getInt(0);  
	                String name = cursor.getString(1);  
	                Integer num = cursor.getInt(2);  
	                Integer price = cursor.getInt(3);  
	                Integer type = cursor.getInt(4);  
	                Integer deal = cursor.getInt(5);  
	                Integer money = cursor.getInt(6);  
	                String date = cursor.getString(7);  
	                r =new Record(  name,  num,   price,
							  type,   deal,   money,   Long.parseLong(date ));
	            }  
	        	cursor.close();  
	        	db.close();  
	        	return r ;  
	        	
	        }

		public String stats(String username) {
			 List<Record> records = new ArrayList<Record>();  
			SQLiteDatabase db = helper.getReadableDatabase();  
         //多单有多少个 num type deal
			//买的多单
			Cursor cursor = db.rawQuery("SELECT   money  FROM account where name=? ", new String[] { username});  
			 Integer account=0 ;
			   while (cursor.moveToNext()) {  
				   account = cursor.getInt(0);  }
			  cursor = db.rawQuery("SELECT _id,name,num,price,type,deal,money,date FROM record where name=? order by _id desc  limit 3 ", new String[] { username});  
			
           String s = ""+account+"\n";  
            while (cursor.moveToNext()) {  
                Integer id = cursor.getInt(0);  
                String name = cursor.getString(1);  
                Integer num = cursor.getInt(2);  
                Integer price = cursor.getInt(3);  
                Integer type = cursor.getInt(4);  
                Integer deal = cursor.getInt(5);  
                Integer money = cursor.getInt(6);  
                String date = cursor.getString(7);  
                Record	r =new Record(  name,  num,   price,
						  type,   deal,   money,   Long.parseLong(date ));
                records.add(r);
                s+=r.toString()+"\n";
                
            }  
            
            //卖出的多单
      //      cursor = db.rawQuery("SELECT sum(num*price) FROM record where name=? and type = 1 and deal=1", null);  
            
            
          //多单 num type deal
            
            cursor.close();  
            db.close();  
            return s; 
		}  

}  

